package com.icehand.payment.pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.icehand.common.code.PaymentCode;
import com.icehand.common.constants.CommonConstants;
import com.icehand.common.enums.PayChannelEnum;
import com.icehand.mybatis.payment.mapper.PayNotifyRecordMapper;
import com.icehand.payment.model.NotifyWrapper;
import com.icehand.payment.model.PayWrapper;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;

/**
 * @author icehand
 */
@Slf4j
public class AliWapPay extends BaseAliPay {
    private static final PayChannelEnum CHANNEL = PayChannelEnum.ALI_WAP_PAY;

    public AliWapPay(RestTemplate restTemplate, PayNotifyRecordMapper payNotifyRecordMapper) {
        super(restTemplate,payNotifyRecordMapper);
    }

    @Override
    public void pay(PayWrapper payWrapper) {
        if(!payWrapper.getPayChannelEnum().equals(CHANNEL)){
            return;
        }

        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl(payWrapper.getConfig().getString(CommonConstants.K_NOTIFY_URL));
        request.setReturnUrl(payWrapper.getExtendMap().get("returnUrl"));

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setOutTradeNo(payWrapper.getBaseOrder().getOrderNo());
        model.setBody(payWrapper.getBaseOrder().getBody());
        model.setProductCode("QUICK_WAP_WAY");
        model.setTotalAmount(payWrapper.getBaseOrder().getAmount().setScale(2, BigDecimal.ROUND_UP).toPlainString());
        model.setSubject(payWrapper.getBaseOrder().getSubject());
        model.setBody(payWrapper.getBaseOrder().getBody());
        model.setTimeExpire(new DateTime(payWrapper.getBaseOrder().getExpireTime()).toString("yyyy-MM-dd HH:mm:ss"));
        request.setBizModel(model);

        AlipayTradeWapPayResponse response;
        try {
            response = createAlipayClient(payWrapper).execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.warn("alipay wap request error:{}",e);
            payWrapper.getBizResult().error(PaymentCode.PAY_FAIL);
            return;
        }

        if(!response.isSuccess()){
            log.warn("alipay wap respons fail:{}", JSONObject.toJSONString(response));
            payWrapper.getBizResult().error(PaymentCode.PAY_FAIL);
        }
        payWrapper.putData(response.getBody());
    }

    @Override
    public void payNotify(NotifyWrapper notifyWrapper) {

    }

    @Override
    public PayChannelEnum getChannel() {
        return CHANNEL;
    }
}
